<?php

namespace app\shop\controller\product;

use app\shop\controller\Controller;
use app\shop\model\product\ProxyCategory as CategoryModel;

/**
 * 商品分类
 */
class ProxyCategory extends Controller
{
    /**
     * 商品分类列表
     */
    public function index()
    {
        $model = new CategoryModel;
        $param = $this->postData();
        $list  = $model->with(['image', 'proxy'])->where($param)->paginate($param);
        // 数量
        $category_count = [
            'using'   => $model->getTotalByWhere(['audit_status' => 1]),
            'audit'   => $model->getTotalByWhere(['audit_status' => 0]),
            'no_pass' => $model->getTotalByWhere(['audit_status' => 2]),
        ];
        return $this->renderSuccess('', compact('list', 'category_count'));
    }

    /**
     * 删除商品分类
     */
    public function delete($id)
    {
        $model = CategoryModel::detail($id);
        if ($model->remove()) {
            return $this->renderSuccess('删除成功');
        }
        return $this->renderError($model->getError() ?: '删除失败');
    }

    /**
     * 编辑商品分类
     */
    public function edit($id)
    {
        // 模板详情
        $model = CategoryModel::detail($id);
        // 更新记录
        if ($model->edit($this->request->post())) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 得到修改图片
     * @return array
     */
    public function image($id)
    {
        $model  = new CategoryModel;
        $detail = $model->with(['image'])->where(['id' => $id])->find();
        return $this->renderSuccess('', compact('detail'));
    }

    /**
     * 审核商品分类
     * @return \think\response\Json
     * @Author joey
     * @date 2024/3/27 10:55
     */
    public function audit()
    {
        $param = $this->postData();
        $model = new CategoryModel;
        if (!isset($param['id'])) {
            return $this->renderError('代理分类id不能为空');
        }
        $param['id'] = is_array($param['id']) ? $param['id'] : [$param['id']];
        $detail      = $model->whereIn('id', $param['id'])->select();
        if ($detail->isEmpty()) {
            return $this->renderError('分类数据不存在');
        }
        $data = ['audit_status' => $param['audit_status'], 'remark' => $param['remark'] ?? ''];
        $num  = 0;
        foreach ($detail as $item) {
            $res = $item->allowField(['audit_status', 'remark'])->save($data);
            if ($res) {
                $num++;
            }
        }
        return $this->renderSuccess($num > 0 ? "审核成功{$num}条" : '审核失败');
    }


}
